package com.isp.org.server.interfaces.rpc.resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.isp.common.model.user.GroupDTO;
import com.isp.common.model.user.PermissionDTO;
import com.isp.common.model.vo.Result;
import com.isp.org.api.client.IResourceClient;
import com.isp.org.api.dto.Resource;
import com.isp.org.api.dto.user.UserVO;
import com.isp.org.api.enums.MenuTypeEnums;
import com.isp.org.server.application.facade.GroupFacade;
import com.isp.org.server.application.facade.MenuFacade;
import com.isp.org.server.application.facade.UserFacade;
import com.isp.org.server.application.facade.UserGroupFacade;
import com.isp.org.server.domain.entity.GroupEntity;
import com.isp.org.server.domain.entity.UserEntity;
import com.isp.org.server.domain.entity.UserGroupEntity;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/3/12 14:31
 */
@DubboService
@RequiredArgsConstructor
public class ResourceClientImpl implements IResourceClient {

    private final MenuFacade menuFacade;
    private final UserFacade userFacade;
    private final UserGroupFacade userGroupFacade;
    private final GroupFacade groupFacade;

    @Override
    public Result<Set<Resource>> resources() {
        return Result.success(menuFacade.findAllByType(MenuTypeEnums.BUTTON.getCode()));
    }

    @Override
    public Result<Set<Resource>> resources(String username) {
        UserVO userVo = userFacade.getByUniqueId(username);
        Set<Resource> resources = menuFacade.queryInRoleIdAndType(userVo.getRoleIds(), MenuTypeEnums.BUTTON.getCode());
        return Result.success(resources);
    }

    @Override
    public Result<List<PermissionDTO>> permissions(PermissionDTO permissionDTO) {
        return null;
    }

    @Override
    public Result<List<GroupDTO>> groups(String username) {
        UserVO user = userFacade.getByUniqueId(username);

        //get groupIds
        List<UserGroupEntity> userGroupList = userGroupFacade.selectByUserId(Long.parseLong(user.getId()));
        Set<String> groupIds = userGroupList.stream().map(UserGroupEntity::getGroupId).collect(Collectors.toSet());

        //get groups
        return Result.success(groupFacade.selectByIds(groupIds));
    }
}
